<?php

namespace App\Services\SuperAdmin;

use App\Exceptions\SuperAdminException;
use Exception;
use Illuminate\Support\Facades\DB;

class ApiService extends BaseSuperAdminService
{

    /**
     * 创建API
     *
     * @return void
     * @throws Exception
     */
    public function createApi(array $params)
    {
        // 查询API是否存在
        $apiDetail = $this->getApisModel()->getItemByPath($params['path']);
        if ($apiDetail) {
            throw new SuperAdminException('API已存在', SuperAdminException::CODE_2001);
        }

        $createData = [
            'path'        => $params['path'],
            'api_group'   => $params['apiGroup'],
            'method'      => $params['method'],
            'description' => $params['description'],
        ];

        // 创建API
        $this->getApisModel()->addItem($createData);
    }

    /**
     * 删除API
     *
     * @return void
     * @throws Exception
     */
    public function deleteApi(array $params)
    {
        // 查询API是否存在
        $apiDetail = $this->getApisModel()->getItemById($params['id']);
        if (empty($apiDetail)) {
            throw new SuperAdminException('API不存在', SuperAdminException::CODE_2002);
        }

        // 删除API
        $this->getApisModel()->deleteItemById($params['id']);
    }

    /**
     * 更新API
     *
     * @return void
     * @throws Exception
     */
    public function updateApi(array $params)
    {
        // 查询API是否存在
        $apiDetail = $this->getApisModel()->getItemById($params['id']);
        if (empty($apiDetail)) {
            throw new SuperAdminException('API不存在', SuperAdminException::CODE_2002);
        }

        $updateData = [
            'path'        => $params['path'],
            'api_group'   => $params['apiGroup'],
            'method'      => $params['method'],
            'description' => $params['description'],
        ];

        // 更新API
        $this->getApisModel()->updateItemById($params['id'], $updateData);
    }

    /**
     * 更新角色API
     *
     * @param array $params
     * @return void
     */
    public function updateAuthorityApi(array $params): void
    {

        $addAuthorityApis = [];
        foreach ($params['apiIds'] as $apiId) {
            $addAuthorityApis[] = [
                'authority_id' => $params['authorityId'],
                'api_id'       => $apiId,
            ];
        }

        DB::transaction(function () use ($params, $addAuthorityApis) {
            // 删除数据
            $this->getAuthorityApisModel()->deleteItemByAuthorityId($params['authorityId']);
            // 添加数据
            $addAuthorityApis && $this->getAuthorityApisModel()->addItem($addAuthorityApis);
        });
    }

    /**
     * 根据id批量删除Api
     *
     * @return void
     * @throws Exception
     */
    public function deleteApisByIds(array $params)
    {
        // 查询是否存在
        // 查询API是否存在
        $apiDetail = $this->getApisModel()->getItemsByIds($params['ids']);
        if (empty($apiDetail)) {
            throw new SuperAdminException('API不存在', SuperAdminException::CODE_2002);
        }

        // 根据ids删除API
        $this->getApisModel()->deleteItemsByIds($params['ids']);
    }

    /**
     * 所有api列表
     *
     * @param array $params
     * @return array
     * @throws Exception
     */
    public function getApiList(array $params): array
    {
        // 总条数
        $total = $this->getApisModel()->getTotal($params);

        // 获取列表
        $list = $this->getApisModel()->getList($params, [
            'id', 'path', 'api_group as apiGroup', 'description', 'method',
        ]);

        return [
            'total'    => $total,
            'list'     => $list,
            'page'     => CURRENT_PAGE,
            'pageSize' => PAGE_SIZE,
        ];
    }

    /**
     * 所有api列表
     *
     * @return array
     * @throws Exception
     */
    public function allApiList(): array
    {
        $list = $this->getApisModel()->getAllList([
            'id', 'path', 'description', 'api_group as apiGroup', 'method',
        ]);
        return [
            'list' => $list,
        ];
    }

    /**
     * 获取权限列表
     *
     * @param array $params
     * @return array
     * @throws Exception
     */
    public function getPolicyPathByAuthorityId(array $params): array
    {
        $apiIds = $this->getAuthorityApisModel()->getApiIdListByAuthorityId($params['authorityId']);
        if (empty($apiIds)) {
            return [];
        }
        $list = $this->getApisModel()->getItemsByIds($apiIds, ['id', 'path', 'method']);
        if (!$list) {
            return [];
        }

        return [
            'list' => $list,
        ];
    }

    /**
     * 详情
     *
     * @return void
     * @throws Exception
     */
    public function detail(array $params): array
    {
        // 详情
        $detail = $this->getApisModel()->getItemById($params['id'], [
            'id', 'path', 'method', 'api_group', 'description',
        ]);

        return [
            'id'          => $detail['id'],
            'path'        => $detail['path'],
            'method'      => $detail['method'],
            'apiGroup'    => $detail['api_group'],
            'description' => $detail['description'],
        ];
    }

}
